package com.cg.system.controller;

import com.cg.system.entity.Result;
import com.cg.system.entity.User;
import com.cg.system.service.UserService;
import com.cg.system.util.JwtUtil;
import com.cg.system.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/login")
    public Result<String> login(String username, String password) {
        // 根据用户名查询用户
        User loginUser = userService.findByUserName(username);

        // 判断用户是否存在
        if (loginUser == null) {
            return Result.error("用户名错误");
        }

        // 判断密码是否正确
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            // 登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);

            // 将 token 作为键，username 作为值存储到 Redis 中
            ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
            valueOps.set(token, loginUser.getUsername(), 2, TimeUnit.HOURS);

            // 维护 username -> token 列表的映射
            ListOperations<String, String> listOps = stringRedisTemplate.opsForList();
            listOps.rightPush(loginUser.getUsername(), token);

            return Result.success(token);
        }

        return Result.error("密码错误");
    }

    @PostMapping("/kick")
    public Result kick(String username) {
        // 检查用户是否存在
        User targetUser = userService.findByUserName(username);

        if (targetUser == null) {
            return Result.error("用户不存在");
        }

        try {
            ListOperations<String, String> listOps = stringRedisTemplate.opsForList();
            // 获取该用户名对应的 token 列表
            List<String> tokens = listOps.range(username, 0, -1);

            if (tokens != null && !tokens.isEmpty()) {
                for (String token : tokens) {
                    // 删除 token -> username 的映射
                    stringRedisTemplate.delete(token);
                }
                // 删除 username -> token 列表
                stringRedisTemplate.delete(username);
                return Result.success("用户已下线");
            }

            return Result.success("用户无活跃令牌");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("踢人失败");
        }
    }
}
